package com.castile.secondkill.controller;

import com.castile.secondkill.error.EmBusinessError;
import com.castile.secondkill.exception.BusinessException;
import com.castile.secondkill.response.CommonResponse;
import com.castile.secondkill.service.OrderService;
import com.castile.secondkill.service.model.OrderModel;
import com.castile.secondkill.service.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Hongliang Zhu
 * @create 2023-03-18 22:31
 */
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 封装下单请求
     *
     * @param itemId 商品id
     * @return 返回值
     */
    @RequestMapping(value = "/createOrder",  method = {RequestMethod.POST})
    @ResponseBody
    public CommonResponse createOrder(@RequestParam(name = "itemId") Integer itemId, @RequestParam(name = "amount") Integer amount, @RequestParam(name = "promoId", required = false) Integer promoId) throws BusinessException {
        // 获取用户的登录信息
        Boolean is_login = (Boolean) request.getSession().getAttribute("IS_LOGIN");
        if (is_login == null || !is_login.booleanValue()) {
            logger.error("用户还没登录");
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        // 获取登录用户的信息
        UserModel userModel = (UserModel) request.getSession().getAttribute("LOGIN_USER");
        OrderModel orderModel = orderService.createOrder(userModel.getId(), itemId, promoId, amount);
        return CommonResponse.create(orderModel);
    }
}
